import THREE from './three.js';

function ClickMap(){
    var self = {};
    self.map = {};
    self.add = function(mesh, func){
        self.map[mesh.uuid] = func;
    };
    self.react = function(rci){
        var obj = null;
        if(rci.length>0){
            obj = rci[0];
            if(self.map[obj.object.uuid]){
                self.map[obj.object.uuid](obj);
            }
        }
    }
    return self;
}

function Ray(){
    var self = {};
    self.raycaster = new THREE.Raycaster();
    self.mouse = new THREE.Vector2();
    self.init_ = function(event){
        self.mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
        self.mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
    };
    self.init = function(camera){
        self.raycaster.setFromCamera( self.mouse, camera );
    };
    self.findClicked = function(group){
        return self.raycaster.intersectObjects( group.children );
    };
    return self;
}

function clickFunc(cb){
    var ray = Ray();
    return function(event){
        ray.init_(event);
        cb(ray, event);
    };
}

export default { clickFunc, ClickMap };